package xty.util;


import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * 反射调用，将实体类转化为map类型工具类
 * Created by XieTianYi on 2017/8/25.
 * @author XieTianYi
 */
public class ComponentUtil {

    /**
     * 获取注解中所有属性
     *
     * @param annotation
     * @return
     */
    public static Map<String, Object> getAnnotationMap(Annotation annotation) throws IllegalAccessException, NoSuchFieldException {
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
        Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");

        //通过反射获取memberValues  这个属性是Map类型 存放着所有的属性。
        memberValues.setAccessible(true);
        return (Map<String, Object>) memberValues.get(invocationHandler);
    }

    /**
     * 将对象注册到bean
     * @param beanName
     * @param object
     */
    public static void registerBean(String beanName, Object object) {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringBeanUtil.getApplicationContext();
        // 获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        // 注册bean
        defaultListableBeanFactory.registerSingleton(beanName, object);
    }
}
